# 迭代器:Python中内置的一种节省空间的工具
# 生成器的本质就是一个迭代器
# 迭代器和生成器的区别: 一个是python自带的,一个是程序员自己写的

# 写一个生成器:

# def func():
#     print(123)
#     return "你好"
# func()

# def func():
#     if 3>2:
#         yield "你好"  # 停
#     if 4>2:
#         yield "我好"
#     yield "大家好"
# g = func()  # 产生一个生成器
# print(g.__next__())
# print(g.__next__())
# print(g.__next__())
# for i in g:
#     print(i)


# while True:
#     try:
#         print(g.__next__())
#     except StopIteration:
#         break

# def foo():
#     for i in range(10):
#         pass
#         yield i
#     count = 1
#     while True:
#         yield count
#         count += 1
# g = foo()
# print(next(g)) # -- 推荐使用
# print(next(g)) # -- 推荐使用
# print(next(g)) # -- 推荐使用
# print(next(g)) # -- 推荐使用
# print(next(g)) # -- 推荐使用

# for i in g:
#     print(i)

# 坑 -- 会产生新的生成器
# print(foo().__next__())
# print(foo().__next__())


# send()  -- 了解
# def func():
#     a = yield "俺是send"
#     print(a)
# g = func()
# print(g.send(None))
# print(g.send(123))

# 生成器应用场景:

# def func():
#     lst = []
#     for i in range(100000):
#         lst.append(i)
#     return lst
# print(func())

# def func():
#     for i in range(100000):
#         yield i
# g = func()
# for i in range(50):
#     print(next(g))

# def func():
#     lst = ["牛羊配","老奶奶花生米","卫龙","虾扯蛋","米老头","老干妈"]
#     for i in lst:
#         yield i
# g = func()
# print(next(g))
# print(next(g))
# print(next(g))
# print(next(g))
# print(next(g))

# def func():
#     lst1 = ["牛羊配","老奶奶花生米","卫龙","虾扯蛋","米老头","老干妈"]
#     lst2 = ["小浣熊","老干爹","亲嘴烧","麻辣烫","黄焖鸡","井盖"]
#     yield from lst1
#     yield from lst2
#
# g = func()
# print(next(g))
# print(next(g))
# print(next(g))

# for i in g:
#     print(i)

# g.__iter__()
# g.__next__()


# 在函数中将return改写成yield就是一个生成器
# yield 会记录执行位置
# return 和 yield 都是返回,
# return 可以写多个,但是只执行一次,yield可以写多个,还可以返回多次
# 一个__next__() 对应 一个yield
# 生成器可以使用for循环获取值
# yield from -- 将可迭代对象元素逐个返回
# 在函数的内部 yield 能将for循环和while循环进行临时暂停